﻿using CommonContainer.Autofac;
using Microsoft.Practices.ServiceLocation;
using Mockery.Core.CommonContainer;
using NUnit.Framework;

namespace CommonContainer.UnitTest.Autofac
{
    [TestFixture]
    public class CommonContainerBuilderTests
    {
        private const int DefaultTestValue = 0;

        [Test]
        public void CommonContainer_InvariantTests()
        {
            TestUtility.AssertMefExport<CommonContainerBuilder, ICommonContainerBuilder>();
        }


        [Test]
        public void CommonContainerBuilder_RegisterInstanceTest()
        {
            const int expectedValue = 2;

            var testInstance = new TestClass {Value = expectedValue};
            
            var builder = new CommonContainerBuilder();
        
            builder.RegisterInstance(typeof(TestClass), (object) testInstance);

            Assert.That(builder.ServiceLocator.GetInstance<TestClass>().Value, Is.EqualTo(expectedValue));
        }

        [Test]
        public void CommonContainerBuilder_RegisterTypeTest()
        {
            var builder = new CommonContainerBuilder();

            builder.RegisterType<TestClass>();

            var serviceLocator = builder.ServiceLocator;

            var testInstance = serviceLocator.GetInstance<TestClass>();
            
            Assert.That(testInstance.Value, Is.EqualTo(DefaultTestValue));

            // make sure that the singleton status is operating
            testInstance.Value = 10;

            Assert.That(serviceLocator.GetInstance<TestClass>().Value, Is.EqualTo(10));
        }

        [Test]
        public void CommonContainerBuilder_VerifyUnregisteredTypeBehaviorTest()
        {
            var builder = new CommonContainerBuilder();

            var serviceLocator = builder.ServiceLocator;

            Assert.Throws<ActivationException>(() => serviceLocator.GetInstance<TestClass>());
        }

        [Test]
        public void CommonContainerBuilder_ValidateNewBehaviorTest()
        {
            var builder = new CommonContainerBuilder();
            builder.RegisterType<TestClass>();

            Assert.Throws<ActivationException>(() => builder.New().ServiceLocator.GetInstance<TestClass>());

        }

        #region Test Class Implementation

        public class TestClass
        {
            public TestClass() 
            {
                Value = DefaultTestValue;
            }

            public int Value { get; set; }
        }

        #endregion
    }
}
